/*
Copyright (c) 2012, 2013 Regents of the University of California
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions 
are met:

 - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the
   distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var datefmt = "%W %M %e, %z %H:%i";
var page_args = getUrlVars();
var current_zoom = {};
timezoneJS.timezone.zoneFileBasePath = "/static/tz";
//timezoneJS.timezone.init() //causing problems in chrome...doesn't appear to be necessary???

function plotInit (no_create, change_dates) {
	if (typeof change_dates == 'undefined'){change_dates = false;}
	$('#btnGrp1').button('reset');
  	//setup the range according to project dates
	if (!change_dates){
		$.ajax({
			type: "GET",
			url: "/pmp/utils/",
			data: {'projectId': sessvars.sessionObj['projectId'], 'utilType': 'tz'},
			success: function(data){
			tz = data	 
			},
			async: false
		});
		$.ajax({
			type: "GET",
			url: "/pmp/utils/",
			data: {'projectId': sessvars.sessionObj['projectId'], 'utilType': 'dates'},
			success: function(data){
				var sd = new Date(data.start_date)
				var ed = new Date(data.end_date)
				var s_offset = sd.getTimezoneOffset() * 60000
				var e_offset = ed.getTimezoneOffset() * 60000
				now = new Date(data.end_date + e_offset)
				then = new Date(data.start_date + s_offset)
			},
			async: false
		});	
	}
  	var converter = new AnyTime.Converter( { format: datefmt});
  	document.getElementById("startDate").value = converter.format(then);
  	document.getElementById("endDate").value = converter.format(now);
  	if (no_create){
		if (document.getElementById('wkdays').checked){advanceTime('wkDays');}
		if (!document.getElementById('alldays').checked){advanceTime('allDays');}
	}
  	if (!no_create) {
    	AnyTime.picker( "startDate", 
    	{ format: datefmt, firstDOW: 0 } );
    	AnyTime.picker( "endDate", 
    	{ format: datefmt, firstDOW: 0 } );  
  	}
  	getTimeRange();
}

function ieqModelChart(data){
	$('#chartContainer').attr('class', 'span7');
	$('#chart').attr('style', '')
	//ieq model map-based
	if ($('#ctRadioMap').is(':checked') || $('#ctImRadioMap').is(':checked')){
    	$('#chart').html(data)
    }
    else {
    	if (data.alert != 'no data'){ 
			$('#legend').html(data.legend);
			chart1 = new Highcharts.Chart({
		         chart: {
		            renderTo: 'chart',
		            type: 'bar'
		         },
		         title: {
		            text: ' '
		         },
		         xAxis: {
		           categories: data.categories,
		     	   //labels: label_style,
		     	   title: {
		           text: ''
		            }
		         },
		         yAxis: {
		            title: {
		               text: 'Percent of readings within assessment class conditions'
		            },
		            max: 100,
		         },
		         legend: {
					backgroundColor: '#FFFFFF',
					reversed: true,
					//align: 'right',
					//verticalAlign: 'middle',
					//layout: 'vertical',
					//y: 20,
					//floating: true,
					borderWidth: 0
				},
		         plotOptions: {
					series: {
						stacking: 'normal',
						cursor: 'pointer',
		                point: {
		                    events: {
		                        click: function() {
		                            var clicked_cat = this.category
									chart2 = new Highcharts.Chart({
								         chart: {
								            renderTo: 'boxplotChart',
								            zoomType: 'xy',
								         },
								         title: {
								            text: 'Assessment class data distributions'
								         },
								         xAxis: {
								           categories: data.bp_categories[clicked_cat],
								     	   //labels: label_style,
								     	   title: {
								           text: ''
								            }
								         },
								         yAxis: {
								            title: {
								               text: '(units vary according to model)'
								            }
								         },
								         credits: {enabled: false},
								         legend: {
								         	enabled: false
										 },
								         series: data.bp_data[clicked_cat],
								      });
								      $( "#boxplotChart" ).dialog( "open" );
		                        }
		                    }
		                }
					}
				},
		         credits: {enabled: false},
		         series: data.seriesData,
		    });
    	}
    	else{
    		alert('No data for this time range or possible configuration error.')
    	} //end check no data
    } //end check for map type
	$('#chart').unblock()
}

function getTimeRange() {
	var start = new timezoneJS.Date(document.getElementById("startDate").value);
  	var end = new timezoneJS.Date(document.getElementById("endDate").value);
  	//the setTimezone function breaks in the current timezoneJS file. It has been edited--but future upgrades of this function will break it again!
  	start.setTimezone(tz)
  	end.setTimezone(tz)
  	naive_start = new Date(document.getElementById("startDate").value)
  	naive_end = new Date(document.getElementById("endDate").value)
  	naive_start = Math.round(naive_start.getTime())
  	naive_end = Math.round(naive_end.getTime())
    start = Math.round(start.getTime());
    end = Math.round(end.getTime());
    global_start = start;
	global_end = end;
  	return [start, end];
}

function setEndNow(start) {
	typeof start != undefined ? start = start : start = false;  
	var converter = new AnyTime.Converter( { format: datefmt });
	if (start){
		var newD = new Date()
		newD = newD.getTime() - 3600000
		newD = new Date(newD) 
		document.getElementById("startDate").value = converter.format(newD);
		document.getElementById("endDate").value = converter.format(new Date());
	}
	else {
		document.getElementById("endDate").value = converter.format(new Date());
	}
}

function advanceTime(forward){
	var start = new Date(document.getElementById("startDate").value).valueOf();
	var end = new Date(document.getElementById("endDate").value).valueOf();
	var period = end - start;
	var wkd = document.getElementById("wkdays").checked;
	var sh = Number(document.getElementById("startHour").value);
	var eh = Number(document.getElementById("endHour").value);
	var ad = document.getElementById("alldays").checked;
	if (forward == true){	
		start = new Date(start + period);
		end = new Date(end + period);
	}
	else if (forward == false) {
		start = new Date(start - period);
		end = new Date(end - period);
	}
	else{
		start = new Date(start)
		end = new Date(end)
	}
	if (ad == false || forward == 'allDays'){
		if (start.getHours() < sh){
			if (forward == true || forward == 'allDays' || forward == 'wkDays'){
				start = new Date(start.setHours(sh))
			}
			else{
				start = new Date(start.valueOf() - 1000*3600*24) //subtract a day
				start = new Date(start.setHours(eh)) //then set back to sh
			}
		}
		else if (start.getHours() > eh){
			if (forward == true || forward == 'allDays'){
				start = new Date(start.valueOf() + 1000*3600*24) //add a day
				start = new Date(start.setHours(sh)) //then set back to sh
			}
			else{
				start = new Date(start.setHours(eh))
			}
		}
	}
	if (wkd == true || forward == 'wkDays'){
		if (forward == true || forward == 'wkDays'){
			//console.log([start.getDay()])
			if (start.getDay() == 0){
				start = new Date(start.valueOf() + 1000*3600*24) //add a day if it is sunday
			}
			else if (start.getDay() == 6){
				start = new Date(start.valueOf() + 1000*3600*24*2) //add two days if it is saturday
			}
		}
		else {
			if (start.getDay() == 0){
				start = new Date(start.valueOf() - 1000*3600*24*2) //substract two days if it is sunday
			}
			else if (start.getDay() == 6){
				start = new Date(start.valueOf() - 1000*3600*24) //substract a day if it is saturday
			}
		}
	}
	if (forward == 'allDays' || forward == 'wkDays'){
			if (end.valueOf() == now.valueOf()) {end = new Date(end.valueOf()-1000*3600*24); end = new Date(end.setHours(eh))}
			else {end = new Date(start.valueOf() + period);}
		}
	else{end = new Date(start.valueOf() + period);}
	var converter = new AnyTime.Converter( { format: datefmt });
	document.getElementById("startDate").value = converter.format(start);
  	document.getElementById("endDate").value = converter.format(end);
  	if (forward == 'allDays'||forward == 'wkDays'){return false;}
  	else{
	  	if ($('#maintain_zoom').is(':checked')){var maintain_zoom = true}
	  	else {var maintain_zoom = false}
	  	analysisPlot(maintain_zoom);
  	}
}

function changeDates(type){
		var start = new timezoneJS.Date(document.getElementById("startDate").value);
		if (type == 'hour'){var now = new timezoneJS.Date(start * 1 + 3600000); if ($('#avgDay').is(':checked') == false){document.getElementById('resample_select').options[0].selected = true; $('#resampleTime').val(document.getElementById('resample_select').options[0].value);}} 
		else if (type == 'day'){var now = new timezoneJS.Date(start * 1 + (3600000 *24)); if ($('#avgDay').is(':checked') == false){document.getElementById('resample_select').options[1].selected = true; $('#resampleTime').val(document.getElementById('resample_select').options[1].value);}}
		else if (type == 'week'){var now = new timezoneJS.Date(start * 1 + (3600000 *24 * 7)); if ($('#avgDay').is(':checked') == false){document.getElementById('resample_select').options[1].selected = true; $('#resampleTime').val(document.getElementById('resample_select').options[1].value);}}
		else if (type == 'month'){var now = new timezoneJS.Date(start * 1 + (3600000 *24*30)); if ($('#avgDay').is(':checked') == false){document.getElementById('resample_select').options[2].selected = true; $('#resampleTime').val(document.getElementById('resample_select').options[2].value);}}
		
		var converter = new AnyTime.Converter( { format: datefmt });
	  	document.getElementById("endDate").value = converter.format(now);
}

function getUrlVars(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++){
         hash = hashes[i].split('=');
         if($.inArray(hash[0], vars)>-1){
             vars[hash[0]]+=","+hash[1];
	         }
	         else{
	             vars.push(hash[0]);
	             vars[hash[0]] = hash[1];
	         }
	    }
	    return vars;
	}

function getCurrentZoom(){
	var axes = plot.getAxes()
	try {
	        var current_zoom = { xaxes: [{ min: axes.xaxis.min, max: axes.xaxis.max }], 
	        				yaxes: [{ min: axes.yaxis.min, max: axes.yaxis.max}, {min: axes.y2axis.min, max: axes.y2axis.max}] };
	    }
    catch(err) {var current_zoom = { xaxes: [{ min: axes.xaxis.min, max: axes.xaxis.max }], yaxes: [{ min: axes.yaxis.min, max: axes.yaxis.max}]};}
    return current_zoom
}

function buildTree(analysisType, stratDevice){
	if (analysisType == 'setpoint'){$("#treeParent").html('<div id="tree"></div>')}
	else {$("#treeParent").html('<h6>Select items to filter data by</h6><div id="tree"></div>')}
	if (typeof $('#id_floor').val() == 'undefined'){var floor = 'none'}
	else{var floor = $('#id_floor').val()}
	$("#tree").jstree({ 
		"json_data" :  {  
         	"ajax" : {  
            "url" : "/pmp/tree/",  
            "data" : {'analysisType': analysisType, 'stratDevice': stratDevice, 'projectId': sessvars.sessionObj['projectId'], 'start_time': global_start, 'end_time': global_end, 'floor':floor},
         }  
     	},  
		"plugins" : [ "themes", "json_data", "ui" ],
		"ui": {"select_multiple_modifier" : "alt"},
	})
   .bind("dblclick.jstree", function(event) {
       var node = $(event.target).closest("li");
       if ($(node).hasClass("jstree-leaf")) {
         $("#tree").jstree("select_node", node);
       } else {
         $("#tree").jstree("toggle_node", node);
       }
     });
}

//get tree selections
function treeSelection(){
	var defer = $.Deferred()
	var selections = {};
	var zones = [];
	var zoneTypes = [];
	var orientations = [];
	var spaceTypes = [];
	var devices = [];
	$($("#tree").jstree("get_selected")).each(
         function () {
           var p = $("#tree").jstree("get_path", this);
           //console.log(p)
           //selections.push(p)
           if(p[0] == "Zone"){zones.push(p[2])}
           else if(p[0] == "Zone Type"){zoneTypes.push(p[1])}
           else if(p[0] == "Orientation"){orientations.push(p[1])}
           else if(p[0] == "Space Type"){spaceTypes.push(p[1])}
           else if(p[0] == "Devices"){devices.push(p[1])}
    	});
    selections['Zones'] = zones
    selections['Zone Types'] = zoneTypes
    selections['Space Types'] = spaceTypes
    selections['Orientations'] = orientations
    selections['Devices'] = devices
    defer.resolve(selections)
    return defer.promise();
}

$.fn.serializeObject = function() {
  var arrayData, objectData;
  arrayData = this.serializeArray();
  objectData = {};

  $.each(arrayData, function() {
    var value;

    if (this.value != null) {
      value = this.value;
    } else {
      value = '';
    }

    if (objectData[this.name] != null) {
      if (!objectData[this.name].push) {
        objectData[this.name] = [objectData[this.name]];
      }

      objectData[this.name].push(value);
    } else {
      objectData[this.name] = value;
    }
  });

  return objectData;
};

function allDays(){
	if (document.getElementById('alldays').checked){
		document.getElementById('startHour').disabled = true;
		document.getElementById('endHour').disabled = true;
		document.getElementById('wkdays').checked = false;
	}
	else {
		document.getElementById('startHour').disabled = false;
		document.getElementById('endHour').disabled = false;
		advanceTime('allDays');
	}
}
function wkDays(){
	if (document.getElementById('wkdays').checked){
		document.getElementById('startHour').disabled = false;
		document.getElementById('endHour').disabled = false;
		document.getElementById('alldays').checked = false;
		advanceTime('wkDays');
	}
	else {
		document.getElementById('startHour').disabled = false;
		document.getElementById('endHour').disabled = false;
	}
}

function mapColumnLAI(){
	if ($('#ctRadioMap').is(':checked')){
		is_map = true;
    	$('#avgDay').attr('disabled',true).attr('checked',false)
		$.ajax({
			type: "GET",
			url: "/pmp/utils/",
			data: {'utilType': 'flr_model', 'projectId':sessvars.sessionObj['projectId']},
			success: function(data){
				$('#analysisOptionsFlr').html(data)
			},
			async: false
		});
		$('#analysisOptionsFlr').show()
	}
	else if ($('#ctImRadioMap').is(':checked')){
		$('#avgDay').attr('disabled',true).attr('checked',false)
		$.ajax({
			type: "GET",
			url: "/pmp/utils/",
			data: {'utilType': 'flr_model','projectId':sessvars.sessionObj['projectId']},
			success: function(data){
				$('#analysisOptionsFlr').html(data)
			},
			async: false
		});
		$('#ieqSaveForm').hide(); 
		is_map = true; 
		$('#analysisOptionsFlr').show();
		$('#analysisOptionsIEQ').show()
	}
	else if ($('#ctImRadioStackedBar').is(':checked')){
		$('#avgDay').attr('disabled',true).attr('checked',false)
		$('#analysisOptionsIEQ').show()
		$('#ieqSaveForm').show();
		$('#analysisOptionsFlr').hide(); 
		is_map = false
		$.ajax({
			type: "GET",
			url: "/pmp/utils/",
			data: {'utilType': 'ieq_model', 'projectId': sessvars.sessionObj['projectId']},
			success: function(data){
				$('#analysisOptionsIEQ').html(data)
			},
			async: false
		});
	}
	else { //column, boxplot, and line
		is_map = false;
		$('#analysisOptionsFlr').hide()
		$('#avgDay').removeAttr('disabled')
	}
	

}


function FtoC(x){ return (x - 32) * 5 / 9; }
function CtoF(x){ return (x * 9 / 5) + 32; }